﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using PPI.Client;
using PPI.Client.Logic.Distribution;
using PPI.Client.Utils;
using PPI.Entities.Distribution;
using PPI.Entities.XML;
using System.Linq;
using PPI.General;

namespace PPI.CRUD
{
    public partial class frmDistributionTransformerEditor : frmBase
    {
        public ETransformer Transformer { get; set; }
        public EDistributionPole Pole { get; set; }
        public EXmlOutboxBase m_OutboxBase { get; set; }

        public frmDistributionTransformerEditor()
        {
            InitializeComponent();
        }

        public void LoadControls()
        {
            string selectOption = "Select an option ...";
            
            DropdownHelper.FillDropdown(ddlClass, GetLookUps(DistributionLookUpType.Class), selectOption);
            DropdownHelper.FillDropdown(ddlPhase, GetLookUps(DistributionLookUpType.Phase), selectOption);
            DropdownHelper.FillDropdown(ddlTransformerType, GetLookUps(DistributionLookUpType.TransformerType), selectOption);
            DropdownHelper.FillDropdown(ddlType, GetLookUps(DistributionLookUpType.Type), selectOption);
            DropdownHelper.FillDropdown(ddlPCBType, GetLookUps(DistributionLookUpType.PCBType), selectOption);
            DropdownHelper.FillDropdown(ddlArrestor, GetLookUps(DistributionLookUpType.Arrestor), selectOption);
            DropdownHelper.FillDropdown(ddlCutout, GetLookUps(DistributionLookUpType.Cutout), selectOption);
            DropdownHelper.FillDropdown(ddlCan, GetLookUps(DistributionLookUpType.Can), selectOption);
            DropdownHelper.FillDropdown(ddlDeterminedBy, GetLookUps(DistributionLookUpType.DeterminedBy), selectOption);

            lstNotes.DataSource = GetLookUps(DistributionLookUpType.Keyword);
        }

        public void LoadTransformer()
        {
            lblVisualInspection.Text = Transformer.CreatedDate.ToString("MM/dd/yyyy");
            txtUtilityNumber.Text = Transformer.UtilityNumber;
            txtSerialNumber.Text = Transformer.SerialNumber;
            txtMenufacturer.Text = Transformer.Manufacturer;
            txtPrimary.Text = Transformer.Primary;
            txtSecondary.Text = Transformer.Secondary;
            txtCondition.Text = Transformer.Comments;
            txtPPM.Text = Transformer.PPM;
            txtTransformerNumber.Text = Transformer.TransformerNumber;
            txtTestNumber.Text = Transformer.TestNumber;
            txtImpeddance.Text = Transformer.Impeddance;
            txtTaps.Text = Transformer.Taps;
            txtPolarity.Text = Transformer.Polarity;
            dtpManufDate.Value = Transformer.ManufDate;

            chkArrestor.Checked = Transformer.Arrestor;
            chkDualRated.Checked = Transformer.DualRated;
            chkPre1978.Checked = Transformer.Pre1978;
            chkCutout.Checked = Transformer.CutOut;
            chkSticker.Checked = Transformer.Sticker;

            ddlClass.SelectedItem = Transformer.Class;
            ddlPhase.SelectedItem = Transformer.Phase;
            ddlPCBType.SelectedItem = Transformer.PCBType;
            ddlType.SelectedItem = Transformer.Type;
            ddlTransformerType.SelectedItem = Transformer.TransformerType;
            ddlArrestor.SelectedItem = Transformer.ArrestorKv;
            ddlCutout.SelectedItem = Transformer.CutOutKv;
            ddlCan.SelectedItem = Transformer.Can;
            ddlDeterminedBy.SelectedItem = Transformer.DeterminedBy;

            position1.SetLatitude(Transformer.Latitude == double.MinValue ? 0 : Transformer.Latitude);
            position1.SetLongitude(Transformer.Longitude == double.MinValue ? 0 : Transformer.Longitude);

            lstNotes.ClearSelected();
            foreach (var note in Transformer.Notes)
            {
                //top.Key = top.Id.ToString();
                lstNotes.SetSelected(lstNotes.Items.IndexOf(note), true);
            }
        }

        private EDistributionLookUp[] GetLookUps(DistributionLookUpType type)
        {
            return LCacheDistributionDataSingleton.Instance.DistributionLookUps.Where(x => x.Type == type).ToArray();
        }


        private void lstImages_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Delete)
                {
                    if (lstImages.SelectedIndex > -1)
                    {
                        //Transformer.Image = new EDistributionPoleImage();
                        LoadImages();

                        if (lstImages.Items.Count == 0)
                            btnSearchImage.Enabled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void LoadImages()
        {
            pbxSelectedImage.Image = null;

            lstImages.DataSource = null;
            lstImages.Items.Clear();

            lstImages.DataSource = Transformer.Images;
            lstImages.DisplayMember = "Title";

            /*if (lstImages.Items.Count > 0)
                btnSearchImage.Enabled = false;*/
        }

        private void lstImages_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lstImages.SelectedIndex > -1)
                {
                    EDistributionPoleImage tmpImage = (EDistributionPoleImage)lstImages.SelectedItem;

                    viewImage(tmpImage);
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void viewImage(EDistributionPoleImage image)
        {
            FileInfo meterImage;

            if (!Pole.isProjectPole)
            {
                if (image.Id == Int32.MinValue)
                    meterImage = new FileInfo(image.FullName);
                else
                    meterImage = new FileInfo(DirHelper.GetImagesDirectory(m_OutboxBase.ConnectionString) + Path.DirectorySeparatorChar + image.FileName);
            }
            else
            {
                meterImage = new FileInfo(image.GetTemporaryFolder());
            }

            if (meterImage.Exists)
            {
                using (Stream s = File.OpenRead(meterImage.FullName))
                    pbxSelectedImage.Image = Image.FromStream(s);
            }
            else
                pbxSelectedImage.Image = null;
        }

        private void frmDistributionTransformerEditor_Load(object sender, EventArgs e)
        {
            LoadControls();
            LoadTransformer();
            LoadImages();

            tabMain.SelectedTab = tabMainTransformer;

            if (lstImages.Items.Count > 0)
                lstImages.SelectedIndex = 0;
            else
            {
                btnSearchImage.Enabled = true;
                pbxSelectedImage.Image = null;
            }
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveTransformer();
            Close();
        }

        private void SaveTransformer()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                ETransformer actualTransformer = Transformer;
                /*
                if (lstImages.Items.Count > 0)
                    actualTransformer.Image = lstImages.Items[0] as EDistributionPoleImage;
                else
                    actualTransformer.Image = null;
                */
                actualTransformer.UtilityNumber = txtUtilityNumber.Text;
                actualTransformer.SerialNumber = txtSerialNumber.Text;
                actualTransformer.Manufacturer  = txtMenufacturer.Text;
                actualTransformer.Primary = txtPrimary.Text;
                actualTransformer.Secondary = txtSecondary.Text;
                actualTransformer.Comments = txtCondition.Text;
                actualTransformer.PPM = txtPPM.Text;
                actualTransformer.TransformerNumber = txtTransformerNumber.Text;
                actualTransformer.TestNumber = txtTestNumber.Text;
                actualTransformer.Impeddance = txtImpeddance.Text;
                actualTransformer.Taps = txtTaps.Text;
                actualTransformer.Polarity = txtPolarity.Text;
                actualTransformer.ManufDate = dtpManufDate.Value;

                actualTransformer.Arrestor = chkArrestor.Checked;
                actualTransformer.DualRated = chkDualRated.Checked;
                actualTransformer.Pre1978 = chkPre1978.Checked;
                actualTransformer.CutOut = chkCutout.Checked;
                actualTransformer.Sticker = chkSticker.Checked;
 
                actualTransformer.Class = ddlClass.SelectedItem as EDistributionLookUp;
                actualTransformer.Phase = ddlPhase.SelectedItem as EDistributionLookUp;
                actualTransformer.PCBType = ddlPCBType.SelectedItem as EDistributionLookUp;
                actualTransformer.Type = ddlType.SelectedItem as EDistributionLookUp;
                actualTransformer.TransformerType = ddlTransformerType.SelectedItem as EDistributionLookUp;
                actualTransformer.ArrestorKv = ddlArrestor.SelectedItem as EDistributionLookUp;
                actualTransformer.CutOutKv = ddlCutout.SelectedItem as EDistributionLookUp;
                actualTransformer.Can = ddlCan.SelectedItem as EDistributionLookUp;
                actualTransformer.DeterminedBy = ddlDeterminedBy.SelectedItem as EDistributionLookUp;

                actualTransformer.Latitude = position1.GetLatitude();
                actualTransformer.Longitude = position1.GetLongitude();

                actualTransformer.Notes.Clear();
                foreach (EDistributionLookUp note in lstNotes.SelectedItems)
                    actualTransformer.Notes.Add(note);

                actualTransformer.Images.Clear();
                foreach (EDistributionPoleImage image in lstImages.Items)
                    actualTransformer.Images.Add(image);

                LTransformer.Update(m_OutboxBase.ConnectionString, Pole, actualTransformer);
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btnSearchImage_Click(object sender, EventArgs e)
        {
            SearchImage();
        }

        private void SearchImage()
        {
            try
            {
                OpenFileDialog _OpenFileDialog = new OpenFileDialog();
                DialogResult _DialogResult = _OpenFileDialog.ShowDialog();

                switch (_DialogResult)
                {
                    case DialogResult.OK:
                    case DialogResult.Yes:
                        FileInfo selectedFile = new FileInfo(_OpenFileDialog.FileName);
                        var img = new EDistributionPoleImage();

                        img.ImageType = DistributionImageType.Transformer;
                        img.FullName = selectedFile.FullName;
                        img.FileName = "Unsaved " + Path.GetFileName(selectedFile.FullName);
                        
                        Transformer.Images.Add(img);

                        LoadImages();
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void chkArrestor_CheckedChanged(object sender, EventArgs e)
        {
            ddlArrestor.Enabled = chkArrestor.Checked;

            if (!chkArrestor.Checked && ddlArrestor.Items.Count > 0)
                ddlArrestor.SelectedIndex = 0;
        }

        private void chkCutout_CheckedChanged(object sender, EventArgs e)
        {
            ddlCutout.Enabled = chkCutout.Checked;

            if (!chkCutout.Checked && ddlCutout.Items.Count > 0)
                ddlCutout.SelectedIndex = 0;
        }
    }
}
